package com.ctbri.vSearch.dao.neo4j;

import com.alibaba.fastjson.JSONObject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;

/**
 * Created by hujie on 16/02/2017.
 */
@Repository
public class Neo4JAccess  {
	
    private static Map<String,Double> queryWordList = null;
    public static Map<String, Double> getQueryWordList() {
        return queryWordList;
    }
    public Neo4JAccess() {

	}
	/**
	 * 从neo4j中查询与参数word相关联的词
	 * @param word
	 * @throws Exception
	 */
    public static Map<String,Double>  queryRelatedWords(Connection conn, String word)throws Exception{
        // word,weight
        Map<String,Double> res = new HashMap<String,Double>();
        String query = "match(n{content:'"
                + word
                + "'})-[r]-(f) RETURN n as node, r as dis ORDER by r.weight DESC limit 30";
        PreparedStatement stmt = null; // 采用预编译，和关系数据库不一样的是,参数需要使用{1},{2},而不是?
        ResultSet rs = null;
        stmt = conn.prepareStatement(query);
        rs = stmt.executeQuery();
        while (rs.next()) {
            // 加入一条边
            JSONObject linkJson = JSONObject.parseObject(rs
                    .getString(2));
            String from = linkJson.getString("from");
            if(from.equals(word)){
                res.put(linkJson.getString("to"),linkJson.getDouble("weight"));
            }
        }
        if (null != rs) {
            rs.close();
        }
        if (null != stmt) {
            stmt.close();
        }
        queryWordList = res;
        return res;
    }
    public void queryRelationMap(){
    	
    }
    
}
